﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.Mvc;

namespace Pyramid.Extentions
{
	public static class EnumExtentions
	{
		public static IEnumerable<SelectListItem> ToSelectList(this Enum enumValue)
		{
			return from Enum e in Enum.GetValues(enumValue.GetType())
				select new SelectListItem
				{
					Selected = e.Equals(enumValue),
					Text = e.ToDescription(),
					Value = e.ToString("d")
				};
		}

		public static string ToDescription(this Enum value)
		{
			var attributes = (DescriptionAttribute[]) value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof (DescriptionAttribute), false);
			return attributes.Length > 0 ? attributes[0].Description : value.ToString();
		}

		public static IEnumerable<SelectListItem> ToSelectList(Type enumType, object selected, bool includeHeader)
		{

			var result = (from Enum e in Enum.GetValues(enumType)
				select new SelectListItem
				{
					Selected = e.Equals(selected),
					Text = e.ToDescription(),
					Value = e.ToString("d")
				}).ToList();
			if (includeHeader)
			{
				result.Insert(0, new SelectListItem {Text = "==所有类型==", Value = ""});
			}
			return result;
		}
	}
}